import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'state.dart';

Reducer<CheckListViewState> buildReducer() {
  return asReducer(
    <Object, Reducer<CheckListViewState>>{
      CheckListViewAction.action: _onAction,
      CheckListViewAction.onGetData: _onGetData,
      CheckListViewAction.setSort: _setSort,
    },
  );
}

CheckListViewState _onAction(CheckListViewState state, Action action) {
  final CheckListViewState newState = state.clone();
  return newState;
}

CheckListViewState _onGetData(CheckListViewState state, Action action) {
  final CheckListViewState newState = state.clone();
  List items = action.payload['items'];
  String tag = action.payload['tag'];
  CheckListModel model = newState.listModels[tag];
  model.currentPage = action.payload['page'];

  if (model.currentPage == 1) {
    model.items = items;
    model.refreshController.finishRefresh();
  } else {
    List tmp = [];
    tmp.addAll(model.items);
    tmp.addAll(items);
    model.items = tmp;
  }
  model.refreshController.finishLoad(noMore: items.length == 0);
  return newState;
}

CheckListViewState _setSort(CheckListViewState state, Action action) {
  final CheckListViewState newState = state.clone()
    ..checkStatus = action.payload
    ..listModels = Map();
  return newState;
}
